package cn.jstars.datatocloud.modules.heart.task;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import cn.jstars.datatocloud.common.cache.Cache;
import cn.jstars.datatocloud.common.consts.Consts.DBConst;
import cn.jstars.datatocloud.common.consts.Consts.DataType;
import cn.jstars.datatocloud.common.utils.DataUtil;
import cn.jstars.datatocloud.modules.base.MqService;
import cn.jstars.datatocloud.modules.heart.service.HeartService;
import cn.jstars.datatocloud.modules.monitor.entity.Toimachinestatus;

/**
 * 心跳数据级联任务类
 * 
 * @author Elvish
 *
 */
public class HeartTask implements Runnable {

	private static final Logger LOGGER = LoggerFactory.getLogger(HeartTask.class);

	private MqService mqService;
	private HeartService heartSerivce;

	public HeartTask(MqService mqService, HeartService heartSerivce) {
		this.mqService = mqService;
		this.heartSerivce = heartSerivce;
	}

	@Override
	public void run() {

		try {
			// 获取心跳数据
			List<Toimachinestatus> dataList = heartSerivce.getHeartDatas();

			// 替换机台编码前缀
			replaceMachinePrefix(dataList);

			// 封装发送数据格式
			String sendMsg = DataUtil.getMessage(DataType.HEART_DATA, DBConst.BASE_DATABASE, DBConst.HEART_TABLE,
					Cache.factoryId, JSONObject.toJSONString(dataList));

			// 发送云端
			mqService.convertAndSend(Cache.cloudMQQueueName, sendMsg);
		} catch (Exception e) {
			LOGGER.error("心跳数据上云异常", e);
		}

	}

	/**
	 * 替换机台编码前缀
	 * 
	 * @param dataList
	 *            心跳数据集合
	 */
	private void replaceMachinePrefix(List<Toimachinestatus> dataList) {
		for (Toimachinestatus tms : dataList) {

			String machineNo = tms.getMachineno();

			tms.setMachineno(Cache.factoryName + "-" + machineNo);
		}
	}

}
